package org.budo.support.web.realip;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.budo.support.lang.util.StringUtil;

import lombok.Getter;
import lombok.Setter;

/**
 * @author limingwei
 */
@Getter
@Setter
public class RealIpRequestWrapper extends HttpServletRequestWrapper {
    private String[] remoteAddrHeaderNames;

    public RealIpRequestWrapper(ServletRequest request, String[] remoteAddrHeaderNames) {
        super((HttpServletRequest) request);

        this.setRemoteAddrHeaderNames(remoteAddrHeaderNames);
    }

    public String getRemoteAddr() {
        String remoteAddrFromHeader = this.getRemoteAddrFromHeader(this);
        return StringUtil.isEmpty(remoteAddrFromHeader) ? super.getRemoteAddr() : remoteAddrFromHeader;
    }

    /**
     * 获取请求者IP
     */
    public String getRemoteAddrFromHeader(HttpServletRequest request) {
        for (String headerName : this.getRemoteAddrHeaderNames()) {
            String ip = request.getHeader(headerName);
            if (null != ip && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
                return ip.split(",")[0]; // 阿里云
            }
        }

        return null;
    }

    public String toString() {
        return super.toString() + ", wrapped(" + this.getRequest() + ")";
    }
}